package com.chen.common.websocket.utils;

import cn.hutool.core.lang.Assert;
import com.chen.base.utils.SpringContextHolder;
import com.chen.base.utils.UrlUtil;
import com.chen.common.websocket.component.AbsWebSocketSessionKey;
import com.chen.common.websocket.constant.WebSocketConstant;
import com.chen.common.websocket.handler.AbsWebSocketHandler;
import org.springframework.web.socket.WebSocketSession;

import java.net.URI;
import java.util.ArrayList;
import java.util.Map;

/**
 * @Author: ChenJinLong
 * @DateTime: 2023/9/13 17:50
 **/
public class WSUitl {

    /**
     * 用于存储WebSocketSession的key
     * 可实现{@link AbsWebSocketSessionKey}的实现类，自定义key
     * @param session websocket
     */
    public static String key(WebSocketSession session){
        Map<String, AbsWebSocketSessionKey> beans = SpringContextHolder.getAppContext()
                .getBeansOfType(AbsWebSocketSessionKey.class);
        if (beans.size() > 0){
            String key = new ArrayList<>(beans.values()).get(0).key();
            return String.format("%s-%s", extremity(session), key);
        }

        return String.format("%s-%s", extremity(session), clientIp(session));
    }

    /**
     * 获取端点
     * @param session websocket
     * @return 端点
     */
    public static String extremity(WebSocketSession session){
        URI uri = session.getUri();
        String value = UrlUtil.getUrlParam(uri.toString(), WebSocketConstant.EXTREMITY);
        Assert.notBlank(value,"【WebSocket】 extremity端点不能为空");

        return value;
    }

    /**
     * 获取客户端ip
     * @param session websocket
     * @return ip
     */
    public static String clientIp(WebSocketSession session){
        return session.getLocalAddress().toString();
    }

    /**
     * 获取WebSocket总连接数
     * @return 总连接数
     */
    public static Integer totalConnectNum(){
        Map<String, AbsWebSocketHandler> wsHandlerMap = wsHandlerMap();
        int total = 0;
        for (AbsWebSocketHandler value : wsHandlerMap.values()) {
            total += value.sessionMap.size();
        }

        return total;
    }

    public static Map<String, AbsWebSocketHandler> wsHandlerMap(){
        return SpringContextHolder.getAppContext().getBeansOfType(AbsWebSocketHandler.class);
    }
}
